# Run ClassStat on a MAXENT output

################################################################################
#load necessary libraries

#list the libraries needed
necessary=c("adehabitat","SDMTools","rgdal","sp")

#check if library is installed
installed = necessary %in% installed.packages()

#if library is not installed, install it
if (length(necessary[!installed]) >=1) install.packages(necessary[!installed], dep = T)

#load the libraries
for (lib in necessary) library(lib,character.only=T)

################################################################################

# Define directory of ASCII template

ASCII.dir = '/home1/99/jc152199/ESA/maxentoutput/'

# Import .csv file with thresholds

thresh=  read.csv(paste(ASCII.dir,'thresh.csv',sep=""),header=T)

# List layers to analyse

layers = list.files(ASCII.dir, pattern='.asc')

# Create a blank dataframe to write out to

stats.out = NULL
ii=0

# Begin a loop to threshold ASCII files and perform Class Stat

for (i in 1:14) 

  {

  # Read in the ASCII

  t.asc = read.asc(paste(ASCII.dir,layers[i],sep="")) 

  # Threshold the ASCII

  t.asc[which(t.asc>=thresh[i,2])]=1
  t.asc[which(t.asc<thresh[i,2])]=0

  # Convert to Binary Matrix

  t.mat = matrix(t.asc, nr=nrow(t.asc), byrow=FALSE)

  # Run Class Stats on Binary Matrix

  stats = ClassStat(t.mat, cellsize=80, bkgd=0)

  # Append Class Stats to a Data Frame

  stats[1,1]=paste(layers[i],sep="")

  stats.out = rbind(stats, stats.out)
                                                                                                                          
  cat(layers[i],'...\n')

  }
  
write.csv(x=stats.out, file=paste(ASCII.dir,'ClassStat.csv',sep=""),row.names=F)



